package com.itheima.reggie.service.impl;

import com.itheima.reggie.dao.ShoppingCartDao;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartDao shoppingCartDao;

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        // 根据userId获取购物车中的数据
        ShoppingCart dbShoppingCart = shoppingCartDao.findUserCartByDishIdOrSetmealId(shoppingCart);
        // 若为空，直接添加
        if (dbShoppingCart == null) {
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartDao.add(shoppingCart);
            dbShoppingCart = shoppingCart;
        } else {
            // 若不为空，修改购物车数量
            dbShoppingCart.setNumber(dbShoppingCart.getNumber() + 1);
            shoppingCartDao.update(dbShoppingCart);
        }

        return dbShoppingCart;
    }

    @Override
    public List<ShoppingCart> getByUserId(Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartDao.findByUserId(userId);
        return shoppingCartList;
    }

    @Override
    public void clean(Long userId) {
        shoppingCartDao.clean(userId);
    }
}
